/*Funktion (checkcollision) zur Berechnung von Kollisionen bei
Pixeln in der Surface SCREEN mit einem Farbwert != Weiß. Sollte
eine Kollision stattfinden, wird xway und yway
des ersteren Objektes (in unserem Fall der Ball)
entsprechend im Vorzeichen verändert werden.*/

#include <SDL/SDL.h>
#include <stdlib.h>

unsigned int getpixel(SDL_Surface *s, int *x, int *y)
{
  return ((unsigned int*)s->pixels)[*y*(s->pitch/sizeof(unsigned int))+*x];
} 

int checkcollision(SDL_Rect ball, SDL_Surface *screen,int xway[],int yway[],int *number,int *step)
{
  int x,y,watch;
  /*Farbwerte werden im Umkreis ueberprueft*/

  /*Zuerst die Kanten*/
  watch=*step;
  if((xway[*number]<-1)||(xway[*number]>1))watch*=2;

  /*Oben Mitte*/
  x=ball.x+(ball.w/2);y=ball.y-watch;
  if((getpixel(screen,&x,&y))!=16777215)
    {
      if(yway[*number]<0)yway[*number]=1;
      else
	if(yway[*number]>0)yway[*number]=-1;
      return 0;
    }
  
  /*Rechts Mitte*/
  x=ball.x+ball.w+watch;y=ball.y+(ball.h/2);
  if((getpixel(screen,&x,&y))!=16777215)
    {
      if(xway[*number]<0)xway[*number]=1;
      else
	if(xway[*number]>0)xway[*number]=-1;
      return 0;
    }
  
  /*Unten Mitte*/
  x=ball.x+(ball.w/2);y=ball.y+ball.h+watch;
  if((getpixel(screen,&x,&y))!=16777215)
    {
      if(yway[*number]<0)yway[*number]=1;
      else
	if(yway[*number]>0)yway[*number]=-1;
      return 0;
    }
  
  /*Links Mitte*/
  x=ball.x-watch;y=ball.y+(ball.h/2);
  if((getpixel(screen,&x,&y))!=16777215)
    { 
      if(xway[*number]<0)xway[*number]=1;
      else
	if(xway[*number]>0)xway[*number]=-1;
      return 0;
    }
  
  /*Dann die Ecken*/

  /*Oben Links*/
  x=ball.x-watch;y=ball.y-watch;
  if((getpixel(screen,&x,&y))!=16777215)
    {
      if(xway[*number]<0)xway[*number]=2;
      else
	if(xway[*number]>0)xway[*number]=-2;
      if(yway[*number]<0)yway[*number]=2;
      else
	if(yway[*number]>0)yway[*number]=-2;
      return 0;
    }
  
  /*Oben Rechts*/
  x=ball.x+ball.w+watch;y=ball.y-watch;
  if((getpixel(screen,&x,&y))!=16777215)
    {
      if(xway[*number]<0)xway[*number]=2;
      else
	if(xway[*number]>0)xway[*number]=-2;
      if(yway[*number]<0)yway[*number]=2;
      else
	if(yway[*number]>0)yway[*number]=-2;
      return 0;
    }
  
  /*Unten Rechts*/
  x=ball.x+ball.w+watch;y=ball.y+ball.h+watch;
  if((getpixel(screen,&x,&y))!=16777215)
    {
      if(xway[*number]<0)xway[*number]=2;
      else
	if(xway[*number]>0)xway[*number]=-2;
      if(yway[*number]<0)yway[*number]=2;
      else
	if(yway[*number]>0)yway[*number]=-2;
     return 0;
    }
  
  /*Unten Links*/
  x=ball.x-watch;y=ball.y+ball.h+watch;
  if((getpixel(screen,&x,&y))!=16777215)
    {
      if(xway[*number]<0)xway[*number]=2;
      else
	if(xway[*number]>0)xway[*number]=-2;
      if(yway[*number]<0)yway[*number]=2;
      else
	if(yway[*number]>0)yway[*number]=-2;
     return 0;
    }
  return 0;
}
